<template>
  <!-- 随访任务 -->
  <section class="main">
    <div class="main_left">
      <el-button
        :disabled="!qxBtns.edit"
        @click="onEdit(null)"
        type="primary"
        icon="el-icon-circle-plus-outline"
        style="width:100%;"
      >新增随访</el-button>
      <!-- <br>
      <h3>随访分组</h3>
      <ul class="visitNav">
        <li v-for="(item,index) in visitStatusCount" :key="index" :class="[item.statisticId==form.status?'active':'']" @click="onGroup(item.statisticId)"><i class="el-icon-s-order"></i>{{item.statisticName}}({{item.count}})</li>
      </ul>-->
      <br />
      <h3>随访状态</h3>
      <ul class="visitNav">
        <li :class="[statusFlog==-1?'active':'']" @click="onVisitType(-1)">
          <i class="el-icon-s-order"></i>
          全部 ({{statusTotal}})
        </li>
        <li
          v-for=" item  in  statusList"
          :key="item.status"
          :class="[item.status==statusFlog?'active':'']"
          @click="onVisitType(item.status)"
        >
          <i class="el-icon-s-order"></i>
          {{VISITSTATUS[item.status]
          ||''}}({{item.count}})
        </li>
      </ul>
    </div>
    <div class="main_right">
      <div class="main_right_c">
        <h2 class="title">
          <!-- 全部随访 -->
          <patientSearch v-model="form.patientId"></patientSearch>
        </h2>
        <div class="visitSearch">
          <el-form :inline="true" @submit.native.prevent="getData(-1)">
            <el-form-item>
              <el-date-picker
                v-model="createTimeRange"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
            <!-- <el-form-item>
              <el-date-picker v-model="visitTimeRange" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" range-separator="至" start-placeholder="随访开始日期" end-placeholder="随访结束日期">
              </el-date-picker>
            </el-form-item>-->
            <!-- <el-form-item>
              <userSearch v-model="form.visitUserId" placeholder="随访人员"></userSearch>
            </el-form-item>-->
            <el-form-item>
              <userSearch v-model="form.operatorId" placeholder="创建人员"></userSearch>
            </el-form-item>
            <el-form-item>
              <userSearch v-model="form.scheduleVisitUserId" placeholder="计划随访人员"></userSearch>
            </el-form-item>
            <el-form-item>
              <deptSearch v-model="form.deptId" placeholder="科室"></deptSearch>
            </el-form-item>
            <el-form-item>
              <doctorSearch
                v-model="form.doctorId"
                :keyword="initData.doctorName"
                placeholder="主管医生"
              ></doctorSearch>
            </el-form-item>
            <!-- <el-form-item>
            </el-form-item>-->
            <el-form-item>
              <el-button type="primary" circle icon="el-icon-search" native-type="submit"></el-button>
            </el-form-item>
          </el-form>
        </div>
        <div v-if="statusFlog==2" class="visitSearch">
            <el-form ref="searchFrom" :rules="searchRule" :model="searchFrom" :inline="true" >
              <el-form-item label="随访导出：" prop="projectId" >
                <el-select v-model="searchFrom.projectId">
                  <el-option v-for="obj in projectList" :label="obj.name" :key="obj.id" :value="obj.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="onExport()" >导出</el-button>
              </el-form-item>
            </el-form>
        </div>
        <ul class="visitList">
          <li v-for="(item,index) in tableList" :key="index">
            <!-- <div class="listLeft">
              <el-image
                v-if="item.headUrl"
                style="width: 120px; height: 120px"
                :src="item.headUrl|imageUrl"
              ></el-image>
              <img v-else style="width: 120px; height: 120px" src="@/img/unknown-avatar.png" />
            </div>-->
            <div class="listRight">
              <div class="listRightC">
                <div>
                  <el-link :underline="false" type="primary">{{item.patientName}}</el-link>
                  <!-- （
                  <span>{{item.sex==1?"男":"女"}}</span>&nbsp;&nbsp;
                  <span v-if="item.age>8">{{item.age}}岁</span>
                  <span v-else>{{item.birthday|toTimeContrast}}</span>）-->
                </div>
                <div
                  class="listText"
                >创建时间：{{item.createTime}} / 创建人员：{{item.createName}} / 科室：{{item.deptName}} / 主管医生：{{item.doctorName}}</div>
                <div
                  class="listText"
                >计划随访日期：{{item.scheduleVisitTime}} / 计划随访人员：{{item.scheduleVisitUserName}} / 随访类型：{{item.visitType}}</div>
                <div v-if="item.status==4" class="listText">取消原因：{{item.cancelReason}}</div>
                <div v-else class="listText">随访内容：{{item.visitContent}}</div>
                <div class="listBtns">
                  <el-button
                    v-if="item.status==1||item.status==0"
                    :disabled="!qxBtns.execute"
                    plain
                    icon="el-icon-document"
                    size="mini"
                    @click="beginVisit(item)"
                  >随访</el-button>
                  <el-button
                    v-if="item.status==0||item.status==1"
                    :disabled="!qxBtns.edit"
                    plain
                    icon="el-icon-edit"
                    size="mini"
                    @click="onEdit(item)"
                  >修改</el-button>
                  <el-button
                    :disabled="!qxBtns.del"
                    v-if="item.status==1||item.status==0"
                    plain
                    icon="el-icon-document-delete"
                    size="mini"
                    @click="onCancel(item)"
                  >取消</el-button>
                  <el-button
                    v-if="item.status==2||item.status==3"
                    plain
                    icon="el-icon-view"
                    size="mini"
                    @click="onEdit(item)"
                  >查看</el-button>
                </div>
                <div class="status-label">
                  <el-badge v-if="item.status==0" type="warning" value="待随访"></el-badge>
                  <el-badge v-else-if="item.status==1" type="success" value="随访中"></el-badge>
                  <el-badge v-else-if="item.status==2" type="primary" value="已结束"></el-badge>
                  <el-badge v-else-if="item.status==3" type="info" value="已取消"></el-badge>
                </div>
              </div>
            </div>
          </li>
        </ul>
        <div v-if="tableList.length == 0" style="color:#999;padding:10px 0;text-align:center;">
          <i class="iconfont iconwushuju" style="font-size:40px;"></i>
          <div>暂无数据</div>
        </div>
        <br />
        <pager v-model="pager" @change-pagenum="getData"></pager>
      </div>
      <!-- <dialogEndVisit v-model="dialogEndVisit" :curItem="curItem" @success="onSuccessEnd"></dialogEndVisit> -->
    </div>
  </section>
</template>
<script>
import enumArr from "./_enum/enum";
import XLSX from 'xlsx';
import {workbook2blob,openDownloadDialog} from '@/_js/excelXlsx';
export default {
  name: "visit",
  components: {
    userSearch: () => import("@/pages/_com/userSearch.vue"),
    patientSearch: () => import("@/pages/_com/patientSearch.vue"),
    doctorSearch: () => import("@/pages/_com/doctorSearch.vue"),
    deptSearch: () => import("@/pages/_com/deptSearch.vue"),
  },
  computed: {
    toTypeCount() {
      const th = this;
      let count = 0;
      th.visitTypeCount.forEach((ele) => {
        count += ele.count;
      });
      return count;
    },
  },
  data() {
    return {
      curItem: null,
      form: {
        visitUserId: "",
        operatorId: "",
        scheduleVisitUserId: "",
        status: "",
        visitTypeId: "",
        patientId: "",
        doctorId: "",
        deptId: "",
      },
      searchFrom:{
        projectId:''
      },
      searchRule:{
        projectId:[{ required: true, message: '请选择随访项目', trigger: 'change' }]
      },
      statusFlog: -1,
      initData: {
        keywordPat: "",
        doctorName: "",
        planUser: "",
      },
      // visitStatusEnum: [],
      visitTimeRange: null,
      createTimeRange: null,
      pager: { pageSize: 10, pageNum: 1, total: 0 },
      qxBtns: {},
      tableList: [],
      visitTypeCount: [], //类型统计
      visitStatusCount: [], //随访状态推统计
      VISITSTATUS: enumArr.VISITSTATUS,
      statusTotal: 0,
      statusList: [],
      projectList:[]
    };
  },
  created() {},
  mounted() {
    this.getQX();
    this.addPageCache("visit");
    this.followUpVisitstatisticstatus();
    this.followUpVisitstatisticvisitType();
    this.getData();
    this.getVisitStatusList();
    this.getAllProjectList();
    // th.getCommonConfigByKey("随访状态").then(res => {
    //   th.visitStatusEnum = res;
    // });
  },
  activated() {
    this.followUpVisitstatisticstatus();
    this.followUpVisitstatisticvisitType();
    this.getData();
    this.getVisitStatusList();
  },
  methods: {
    //开始随访
    beginVisit(obj) {
      let j = {
        id: this.jiaMi(obj.id),
      };
      let js = this.$utils.JsonToUrl(this.getUrlToken(j));
      this.addNavMenu(obj.patientName+"的随访", "/page/visitDetail?" + js, "");
      this.$router.push({
        path: "visitDetail",
        query: this.getUrlToken(j),
      });
    },
    //取消随访
    onSuccessEnd() {
      const th = this;
      th.curItem.status = 4;
      let statusCount = th.visitStatusCount.find((d) => {
        return d.statisticId == 4;
      });
      if (statusCount) {
        statusCount.count += 1;
      }
    },
    //获取数据
    getData() {
      let th = this;
      let j = {
        startDate: "",
        endDate: "",
      };
      const createTimeRange = this.createTimeRange;
      if (createTimeRange) {
        j.startDate = createTimeRange[0];
        j.endDate = createTimeRange[1];
      }
      Object.assign(j, th.pager);
      Object.assign(j, th.form);
      th.showLoading();
      th.$api
        .getVisitRecordByPage(j)
        .then((res) => {
          if (res.executed) {
            th.tableList = res.dataBody ? res.dataBody.list : [];
            th.pager.total = res.dataBody.total;
          }
          th.showLoading(false);
        })
        .catch((res) => {
          th.showLoading(false);
        });
    },
    //状态统计
    followUpVisitstatisticstatus() {
      const th = this;
      let j = {};
      th.$api.followUpVisitstatisticstatus(j).then((res) => {
        th.visitStatusCount = res.data;
      });
    },
    //类型统计
    followUpVisitstatisticvisitType() {
      const th = this;
      let j = {};
      th.$api.followUpVisitstatisticvisitType(j).then((res) => {
        if (res.executed) {
          th.visitTypeCount = res.data;
        }
      });
    },
    //设置随访类型
    onVisitType(id) {
      this.form.status = id == -1 ? "" : id;
      this.statusFlog = id;
      this.pager.pageNum = 1;
      this.getData();
    },
    //取消
    onCancel(obj) {
      //
      this.$prompt("取消原因", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /\S/,
        inputErrorMessage: "请输入取消原因",
      }).then(({ value }) => {
        this.$api
          .cancelVisitRecord({ cancelReason: value, id: obj.id })
          .then((res) => {
            if (res.executed) {
              this.$message.success(res.message);
              this.getData();
              this.getVisitStatusList();
            } else {
              this.$message.error(res.message);
            }
          });
      });
    },
    //查看详情
    onEdit(obj) {
      if (obj) {
        const {
          id,
          patientName,
          doctorName,
          scheduleVisitUserName,
          status,
        } = obj;
        let q = {
          id: this.jiaMi(id),
          patientName: patientName,
          docName: doctorName,
          planUser: scheduleVisitUserName,
          status: status,
        };
        //已完成
        if (q.status == 2) {
          let js = this.$utils.JsonToUrl(this.getUrlToken(q));
          this.addNavMenu(obj.patientName+"的随访详情", "/page/completeVisitDetail?" + js, "");
          this.$router.push({
            path: "completeVisitDetail",
            query: this.getUrlToken(q),
          });
        } else if (q.status == 3) {
          let js = this.$utils.JsonToUrl(this.getUrlToken(q));
          this.addNavMenu(obj.patientName+"的随访详情", "/page/cancelVisitDetail?" + js, "");
          this.$router.push({
            path: "cancelVisitDetail",
            query: this.getUrlToken(q),
          });
        } else {
          let js = this.$utils.JsonToUrl(this.getUrlToken(q));
          this.addNavMenu("编辑随访", "/page/editVisit?" + js, "");
          this.$router.push({
            path: "editVisit",
            query: this.getUrlToken(q),
          });
        }
      } else {
      let js = this.$utils.JsonToUrl(this.getUrlToken({ id: 0 }));
      this.addNavMenu("编辑随访", "/page/editVisit?" + js, "");
        this.$router.push({
          path: "editVisit",
          query: this.getUrlToken({ id: 0 }),
        });
      }
    },
    //获取随访状态列表
    getVisitStatusList() {
      this.$api.getVisitStatusList().then((res) => {
        const list = res.dataBody;
        this.statusList = list;
        this.statusTotal = list.reduce((t, c) => {
          return (t += c.count);
        }, 0);
      });
    },
    /**
     * 获取随访项目
     */
    getAllProjectList() {
      this.$api
        .getAllProjectList({
          projectId: this.searchFrom.projectId,
        })
        .then((res) => {
          if (res.executed) {
            this.projectList = res.dataBody;
          }
        });
    },
    onExport(){
      this.$refs["searchFrom"].validate(valid=>{
         if(valid){
           let j = {
            startDate: "",
            endDate: "",
          };
          const createTimeRange = this.createTimeRange;
          if (createTimeRange) {
            j.startDate = createTimeRange[0];
            j.endDate = createTimeRange[1];
          }
          Object.assign(j, this.form);
           this.$api.getVisitResultExport({projectId:this.searchFrom.projectId,...j}).then(res=>{
             if(res.executed){
               let list=res.dataBody;
               const childList=list[0].list;
               let newArr=[];
               list.map(it=>{
                  if(it.list.length>0){
                     it.list.map((obj,index)=>{
                       it['value'+parseInt(index)]=obj.value;
                     })
                  }
               })
               if(childList.length>0){
                  childList.forEach((it,index)=>{
                    it['value'+parseInt(index)]=it.value;
                    it['name'+parseInt(index)]=it.name;
                    newArr.push({key:'value'+parseInt(index),name:it.name})
                  })
               }
               let dataArr=[
                  { key: "deptName", name: "科室" },
                  { key: "doctorName", name: "医生" },
                  { key: "projectName", name: "随访项目" },
                  { key: "operatorName", name: "创建人" },
                  { key: "visitUserName", name: "计划执行人" },
                  { key: "projectTypeName", name: "随访类型" },
                  { key: "createTime", name: "创建日期" },
                  { key: "scheduleVisitTime", name: "计划随访日期" },
                  { key: "scheduleVisitUserName", name:'随访人员'},
                  { key: "visitTime", name:'随访日期'},
                  { key: "visitWay", name: "随访方式" },
                ]
                dataArr=dataArr.concat(newArr);
                
                const headerTitle={};
                dataArr.map(it=>{
                  headerTitle[it.key]=it.name;
                })
                const newData = [headerTitle, ...list];
                var sheet1 = XLSX.utils.json_to_sheet(newData,{skipHeader:true});
                var wb = XLSX.utils.book_new();
                XLSX.utils.book_append_sheet(wb, sheet1, "随访统计");
                const workbookBlob = workbook2blob(wb);
                openDownloadDialog(workbookBlob, `随访统计.xlsx`);
             }
           })
         }
      })
    }
  },
};
</script>
<style lang="scss" scoped>
.main {
  width: 100%;
  height: 100%;
  overflow: hidden;
  &::after {
    display: block;
    clear: both;
    visibility: hidden;
    height: 0;
    overflow: hidden;
    content: "";
  }
  .main_left {
    width: 220px;
    float: left;
    position: relative;
    margin-right: -220px;
    height: 100%;
    overflow: auto;
  }
  .main_right {
    width: 100%;
    float: right;
    height: 100%;
    overflow: auto;
    .main_right_c {
      margin-left: 250px;
      .title {
        margin: 0 0 20px 0;
      }
    }
  }
}
.visitNav,
.visitNav li {
  list-style: none;
  margin: 0;
  padding: 0;
}
.visitNav li {
  line-height: 38px;
  padding: 0 15px;
  border-radius: 4px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  &:hover {
    background: #f6f6f6;
  }
  i {
    margin-right: 10px;
  }
}
.visitNav li.active {
  background: #f56c6c;
  color: #fff;
}
.visitSearch {
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}
.visitList {
  li {
    padding: 20px 0;
    border-bottom: 1px solid #eee;
    &::after {
      display: block;
      clear: both;
      visibility: hidden;
      height: 0;
      overflow: hidden;
      content: ".";
    }
    .listLeft {
      width: 120px;
      float: left;
      position: relative;
      margin-right: -120px;
    }
    .listRight {
      width: 100%;
      float: right;
      .listRightC {
        // margin-left: 150px;
        position: relative;
        .status-label {
          position: absolute;
          right: 15px;
          top: 0;
        }
      }
    }
  }
  .el-link {
    font-size: 18px;
  }
  .listBtns {
    margin-top: 7px;
  }
}
.listText {
  color: #888;
  line-height: 1.74;
}
</style>